package com.briup.jdbc.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

import com.briup.jdbc.extannotation.ExtDelete;
import com.briup.jdbc.extannotation.ExtInsert;
import com.briup.jdbc.extannotation.ExtSelect;
import com.briup.jdbc.extannotation.ExtUpdate;
import com.briup.jdbc.handler.invoke.DeleteInvoke;
import com.briup.jdbc.handler.invoke.InsertInvoke;
import com.briup.jdbc.handler.invoke.SelectInvoke;
import com.briup.jdbc.handler.invoke.UpdateInvoke;
import com.briup.jdbc.interfaces.IInvoke;

public class JDBCHandler implements InvocationHandler {

	private Connection conn;
	// 目标对象
	private Object target;
	// 自动事务开关ture表示自动，false表示手动
	private boolean autoCommit = true;

	public JDBCHandler(Object target) {
		super();
		this.target = target;
	}

	public JDBCHandler(Connection conn, Object target) {
		super();
		this.conn = conn;
		this.target = target;
		autoCommit = false;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		IInvoke iInvoke = null;
		if (method.getAnnotation(ExtSelect.class) != null) {
			iInvoke = new SelectInvoke(conn,autoCommit);
		} else if (method.getAnnotation(ExtInsert.class) != null) {
			iInvoke = new InsertInvoke(conn,autoCommit);
		} else if (method.getAnnotation(ExtUpdate.class) != null) {
			iInvoke = new UpdateInvoke(conn,autoCommit);
		} else if (method.getAnnotation(ExtDelete.class) != null) {
			iInvoke = new DeleteInvoke(conn,autoCommit);
		} else {
			throw new Exception("the method is not exist @ExtSelect!");
		}
		return iInvoke.invoke(proxy, method, args);
	}

}
